package com.gengzp.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;

/**
 * @ClassName RestTemplateUtils
 * @Description 远程调用restTemplate工具类
 * @Author gengzp
 * @Date 2025/5/30 23:58
 */
public class RestTemplateUtils {

    private static final Logger logger = LoggerFactory.getLogger(RestTemplateUtils.class);

    private static final RestTemplate restTemplate = initRestTemplate();

    private static RestTemplate initRestTemplate() {
        // 创建基于Apache HttpClient的请求工厂
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        // 配置连接超时时间（毫秒）
        requestFactory.setConnectTimeout(5000);
        // 配置连接请求超时时间（毫秒）
        requestFactory.setConnectionRequestTimeout(30000);

        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse response) throws IOException {
                // 始终返回false，表示没有错误，不触发异常
                return false;
            }

            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                // 空实现，不处理错误
            }
        });
        return restTemplate;
    }

    private RestTemplateUtils() {
    }

    /**
     * 发送GET请求
     *
     * @param url          请求URL
     * @param responseType 返回类型
     * @param <T>          泛型
     * @return 响应结果
     */
    public static <T> T get(String url, Class<T> responseType) {
        return restTemplate.getForEntity(url, responseType).getBody();
    }

    /**
     * 发送POST请求
     *
     * @param url          请求URL
     * @param requestBody  请求体
     * @param responseType 返回类型
     * @param <T>          泛型
     * @return 响应结果
     */
    public static <T> T post(String url, Object requestBody, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);

        return restTemplate.postForEntity(url, entity, responseType).getBody();
    }

    /**
     * 发送POST请求
     *
     * @param url            请求URL
     * @param requestHeaders 请求头
     * @param requestBody    请求体
     * @param responseType   返回类型
     * @param <T>            泛型
     * @return 响应结果
     */
    public static <T> T post(String url, HttpHeaders requestHeaders, Object requestBody, Class<T> responseType) {
        try {
            return restTemplate.postForEntity(
                    url, new HttpEntity<>(requestBody, requestHeaders), responseType).getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 发送表单POST请求
     *
     * @param url          请求URL
     * @param params       表单参数
     * @param responseType 返回类型
     * @param <T>          泛型
     * @return 响应结果
     */
    public static <T> T postForm(String url, Map<String, Object> params, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
        if (params != null) {
            params.forEach(formData::add);
        }

        return restTemplate.postForEntity(
                        url, new HttpEntity<>(formData, headers), responseType)
                .getBody();
    }

}
